package cn.imvc.app.controllers.order;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import cn.imvc.app.commons.SystemConfig;
import cn.imvc.app.domains.OrderState;
import cn.imvc.app.entities.Goods;
import cn.imvc.app.entities.Orders;
import cn.imvc.app.entities.StorageOrder;
import cn.imvc.app.entities.UserSeller;
import cn.imvc.app.models.LoggingModel;
import cn.imvc.app.models.OrdersModel;
import cn.imvc.app.models.StorageOrderModel;
import cn.imvc.app.models.UserModel;
import cn.imvc.app.models.UserSellerModel;
import cn.imvc.core.DialogBean;
import cn.imvc.core.Render;
import cn.imvc.data.domain.ViewRequest;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class StorageOrderControllerImpl implements StorageOrderController {
	static Logger logger = Logger.getLogger(StorageOrderControllerImpl.class);
	@Autowired
	OrdersModel ordersModel;
	@Autowired
	StorageOrderModel storageOrderModel;
	@Autowired
	SystemConfig systemConfig;
	@Autowired
	UserModel userModel;
	@Autowired
	UserSellerModel userSellerModel;
	@Autowired
	LoggingModel loggingModel;
	
	public Page<StorageOrder> page;
	public Goods goods;
	public StorageOrder storageOrder;
	public Orders orders;
	public ViewRequest viewRequest;
	public int id;
	public int[] ids;
	public Map<Byte, String> orderState = OrderState.elMap;
	public String sellerName;
	public String storageName;
	public String expressName;
	public String memberName;
	public Double freight;
	public Double overFreight;
	public String filePath;
	public int isCover;
	private int sellerId;
	
	public void setSellerId(int sellerId) {
		this.sellerId = sellerId;
	}
	
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public void setIsCover(int isCover) {
		this.isCover = isCover;
	}
	
	public void setFreight(Double freight) {
		this.freight = freight;
	}

	public void setOverFreight(Double overFreight) {
		this.overFreight = overFreight;
	}

	public void setMemberName(String memberName) {
		this.memberName = memberName;
	}

	public void setSellerName(String sellerName) {
		this.sellerName = sellerName;
	}

	public void setStorageName(String storageName) {
		this.storageName = storageName;
	}

	public void setExpressName(String expressName) {
		this.expressName = expressName;
	}

	public void setOrdersModel(OrdersModel ordersModel) {
		this.ordersModel = ordersModel;
	}

	public void setStorageOrderModel(StorageOrderModel storageOrderModel) {
		this.storageOrderModel = storageOrderModel;
	}

	public void setPage(Page<StorageOrder> page) {
		this.page = page;
	}

	public void setGoods(Goods goods) {
		this.goods = goods;
	}

	public void setStorageOrder(StorageOrder storageOrder) {
		this.storageOrder = storageOrder;
	}

	public void setOrders(Orders orders) {
		this.orders = orders;
	}

	public void setViewRequest(ViewRequest viewRequest) {
		this.viewRequest = viewRequest;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setIds(int[] ids) {
		this.ids = ids;
	}

	public void setOrderState(Map<Byte, String> orderState) {
		this.orderState = orderState;
	}

	public String search() {
		// TODO Auto-generated method stub
		return null;
	}

	public String index() {
		page=storageOrderModel.find(viewRequest);
		return "storage-order/index";
	}

	public String show() {
		// TODO Auto-generated method stub
		return null;
	}

	public String editNew() {
		// TODO Auto-generated method stub
		return null;
	}

	public String create() {
		// TODO Auto-generated method stub
		return null;
	}

	public String edit() {
		storageOrder=storageOrderModel.get(id);
		if(storageOrder.getDeliveryTime() == null){
			storageOrder.setDeliveryTime(new Date());
			Calendar calendar = new GregorianCalendar(); 
			calendar.setTime(new Date());
			calendar.add(calendar.DATE, systemConfig.getReceiptEndOfDays());
			storageOrder.setReceiptEndTime(calendar.getTime());
		}
		return "storage-order/edit";
	}

	public String update() {
		storageOrderModel.update(storageOrder);
		loggingModel.info(logger, "更新发货信息成功二级订单编号："+storageOrder.getCode());
		return Render.json(new DialogBean("200", "更新发货信息成功","", ""));
	}

	public String destroy() {
		// TODO Auto-generated method stub
		return null;
	}

	public String destroyBatch() {
		// TODO Auto-generated method stub
		return null;
	}
	
	public String editMail(){
		storageOrder = storageOrderModel.get(id);
		return "storage-order/edit";
	}

	public String exportOrder() {
		storageOrderModel.updateExportOrder(id);
		return null;
	}

	public String delivered() {
		storageOrder.setFreight((int)(freight*100));
		storageOrder.setOverweightFreight((int)(overFreight*100));
		boolean state = false;
		try {
			state = storageOrderModel.updateDelivered(storageOrder);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(state){
			loggingModel.info(logger, "发货成功二级订单编号："+storageOrder.getCode());
			return Render.json(new DialogBean("200", "发货成功","goodsOrder_show"));
		}else{
			return Render.json(new DialogBean("300", "发货失败","goodsOrder_show"));
		}
	}

	@Override
	public String impXls() {
		return "storage-order/imp";
	}
	
	@Override
	public String updateExpress() {
		String rederMsg = "处理出错";
	    Workbook rwb = null;
	    StringBuffer sb = new StringBuffer();
	    InputStream stream;
		try {
			stream = new FileInputStream(systemConfig.getImagePath()+File.separatorChar+ filePath);
			rwb = Workbook.getWorkbook(stream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (BiffException | IOException e) {
			e.printStackTrace();
		}
	    Sheet sheet = rwb.getSheet(0);  
	    //表头的目录不需要，从1开始
	    for(int i=1; i<sheet.getRows(); i++){
	    	String orderCode = sheet.getCell(0,i).getContents().trim();
	    	String expressCode = sheet.getCell(sheet.getColumns()-1,i).getContents().trim();
	    	if("".equals(orderCode) || "".equals(expressCode)){
	    		continue;
	    	}
	    	List<StorageOrder> storageOrders = storageOrderModel.findByCode(orderCode);
	    	if(storageOrders.size() == 0){
	    		sb.append(orderCode+"的二级订单编号不存在\\n");
	    	}else{
	    		StorageOrder storageOrder =  storageOrders.get(0);
				
	    		if(storageOrder.getState() == OrderState.Delivery.getValue() || (storageOrder.getState() == OrderState.Delivered.getValue() && isCover == 1?true:false)){
	    			storageOrder.setDeliveryTime(new Date());
		    		Calendar calendar = new GregorianCalendar(); 
					calendar.setTime(new Date());
					calendar.add(calendar.DATE, systemConfig.getReceiptEndOfDays());
					storageOrder.setReceiptEndTime(calendar.getTime());
					storageOrder.setExpressCode(expressCode);
	    			storageOrder.setState(OrderState.Delivered.getValue());
	    			storageOrderModel.updateSaveAndSync(storageOrder);
	    			loggingModel.info(logger, "更新订单"+orderCode+"的快递单号为："+expressCode);
	    			sb.append("更新订单"+orderCode+"的快递单号为"+expressCode+"\\n");
	    		}else{
	    			sb.append(orderCode+"订单，没有更新\\n");
	    		}
	    	}
	    }
	    rederMsg = sb.toString();
		
		return Render.json("{'statusCode':'200','message':'导入成功','msg':'"+rederMsg+"'}");
	}
	
	/**
	 * 仓库订单批量导出页面
	 */
	public String batchExcelExportUI(){
		int theUserId = userModel.getSessionUser().getId();
		List<UserSeller> userSellerList = userSellerModel.findByUserId(theUserId);
		if(userSellerList.size() <= 0 ){
			sellerId = 0;
		}else{
			sellerId = userSellerList.get(0).getSeller().getId();
		}
		if(viewRequest == null){
			viewRequest = new ViewRequest();
		}
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, +1);//昨天
        String theDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
		viewRequest.getParams().put("payTimeBegin", new SimpleDateFormat("yyyy-MM-dd").format(new Date().getTime()));
		viewRequest.getParams().put("payTimeEnd", theDate);
		
		return "storage-order/batchExcelExport";
	}
	
	public String batchExcelExport(){
		 storageOrderModel.updateBatchExcelExport(viewRequest);
		 return null;
	}

	public int getSellerId() {
		return sellerId;
	}
}
